import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/models/local_data/random_color.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/tweet/tweet_local_search_friend.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/tweet/osc_tweet_pick_user_widget.dart';
import 'package:osc/ui/widgets/tweet/osc_tweet_text_portrait.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

class TweetPickFriends extends StatefulWidget {
  @override
  _TweetPickFriendsState createState() => _TweetPickFriendsState();
}

class _TweetPickFriendsState extends State<TweetPickFriends> {

  int maxCount = 10;
  int count = 0;

  List<OscUser> localUsers;

  List<OscUser> selectUsers;

  @override
  void initState() {
    super.initState();
    localUsers = OscUserManager().getRecentUserList();
    selectUsers = List();
  }
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: "选择好友",
        actions: <Widget>[
          SmallWidgets.buildAction(
              data: "确定(${selectUsers.length}/$maxCount)",
              onTap: (){
                saveRecentUser();
                PopResult result = PopResult(id: PopResult.ID_PICK_FRIEND, success: true, extract:  {"friends" : selectUsers});
                Navigator.pop(context, result);
              },
          ),
        ],
        body: buildBody(),
    );
  }

  buildBody(){
    return ListView(
      children: <Widget>[
        buildSearch(),
        buildSelectUsers(),
        buildRecentlyContactsTab(),
        buildRecentlyContacts(),
      ],
    );
  }

  buildSearch(){
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black12),
      ),
      child: IconButton(
        alignment: Alignment.centerLeft,
          icon: Row(
            children: <Widget>[
              Image.asset(PdUtil.getImagePath("ic_search"), width: Dimens.view_item_icon_height_small, fit: BoxFit.contain,),
              Text("搜索", style: MyTextStyle.HINT,),
            ],
          ),
          onPressed: (){
            jump2Page(TweetLocalSearchFriends());
          },
      ),
    );
  }

  buildSelectUsers(){
    return Container(
      height: Dimens.view_item_height_biggest,
      padding: EdgeInsets.all(Dimens.gap_view_big),
      color: Colors.white,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (BuildContext context, int index){
          OscUser user = selectUsers.elementAt(index);
          return Container(
            margin: EdgeInsets.only(right: Dimens.gap_view_normal),
            width: Dimens.view_item_height_small,
            height: Dimens.view_item_height_small,
            child: GestureDetector(
              onTap: (){
                selectUsers.removeAt(index);
                refreshView();
              },
              child: buildSelectUserItem(user),
            ),
          );
        },
        itemCount: selectUsers.length,
      ),
    );
  }

  buildSelectUserItem(OscUser user){
    if(StringUtil.isEmpty(user.portrait)){
      return OscTweetTextPortrait(name: user.name, color: user.color,);
    } else {
      return SmallWidgets.buildCircleImage(url: user.portrait);
    }
  }

  buildRecentlyContactsTab(){
    return Offstage(
      offstage: localUsers.length == 0,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_small),
        child: Text("最近联系人", style: MyTextStyle.LIST_BODY,),
      ),
    );
  }

  buildRecentlyContacts(){
    return ListView.separated(
        shrinkWrap: true,
        primary: false,
        itemBuilder: (BuildContext context, int index){
          return buildUserItem(localUsers.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index){
          return SmallWidgets.buildLine();
        },
        itemCount: localUsers.length,
    );
  }

  buildUserItem(OscUser user){
    return OscTweetPickUserWidget(
      user: user,
      showCheckBox: true,
      onTap: (){
        user.checked = !user.checked;
        if(user.checked){
          selectUsers.add(user);
        } else {
          selectUsers.remove(user);
        }
        refreshView();
      },
    );
  }


  refreshView(){
    if(mounted){
      setState(() {

      });
    }
  }

  jump2Page(Widget page){
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result){
      if(result != null && result.success){
        switch(result.id){
          case PopResult.ID_PICK_FRIEND:
            OscUser user = result.extract["friend"];
            if(user != null){
              if(selectUsers.length < 10) {
                user.color = RandomColor().getRandomColor();
                selectUsers.add(user);
              } else {
                showTips("您一次最多可以选择10个好友");
              }
            }
            refreshView();
            break;
        }
      }
    });
  }

  saveRecentUser(){
    if(selectUsers != null){
      for(OscUser user in selectUsers){
        if(user.id != null || user.id > 0){
          user.checked = false;
          OscUserManager().addRecentUser(user);
        }
      }
    }
  }


  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
